<?php

namespace app\api\controller;

use app\admin\model\ServersUser;
use app\admin\model\SystemConfig;
use app\api\model\Goods;
use app\api\model\GoodsProduct;
use app\api\model\Order as ModelOrder;
use app\api\model\OrderItem;
use app\api\model\ServerUser;
use app\api\model\ServiceTime;
use app\api\model\SuserItem;
use app\api\model\User;
use app\api\model\UserAddress;
use app\common\controller\ApiController;
use think\App;
use think\facade\Db;
use think\facade\Env;
use WeChat\Pay;
use \app\admin\traits\Curd;
use app\api\model\AfterOrder;
use app\api\model\AfterOrderItem;
use app\api\model\AttachOrder;
use app\api\model\Finance;
use app\api\model\OrderRecord;

class Distributor extends ApiController
{
    protected $noNeedLogin = [
        "get_distributor_agreement",
        "get_distributor_poster"
        
    ];
    protected $mustLogin = [];
    protected $counter = 0;

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    /**
     *  申请分销商
     */
    public function apply_distributor()
    {
        $param = $this->request->param();
        if (empty($param['name'])) {
            $this->error('请填写姓名');
        }
        if (empty($param['card'])) {
            $this->error('请填写身份证号');
        }
        if (empty($param['phone'])) {
            $this->error('请填写手机号');
        }
        if (empty($param['address'])) {
            $this->error('请填写地址 ');
        }
        //拒绝后重新提交
        if(empty($param['fid'])){
            $param['create_time'] = time();
            $param['uid'] = $this->uid;
            if(Db::name('distributor')->where('uid',$this->uid)->find()) $this->error('您已经申请过分销商,请不要重复提交!');
            if(Db::name('distributor')->insert($param)) 
            {
                $this->success('提交申请成功,请等待管理员审核!');
            }
        }else{
            $flag = Db::name('distributor')->where('id',$param['fid'])->find();
            if ($flag['examine'] != 3) {
                $this->error('不能重新申请');
            }
            $fid = $param["fid"];
            unset($param["fid"]);
            $param['examine'] = 0;
            Db::name('distributor')->where('id',$fid)->update($param);
            $this->success('提交申请成功,请等待管理员审核!');
        }
        
    }

    //拒绝重新申请显示
    public function re_apply(){
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('分销商id不能为空');
        }
        $list = Db::name('distributor')->where('id',$param['fid'])->find();
        $this->success('获取成功',$list);
    }

    //判断是否是分销商
    public function is_distributor(){
        $flag = Db::name('distributor')->where('uid',$this->uid)->find();
        if (empty($flag)) {
            $this->success("不是");
        }else{
            $this->success("是",$flag);
        }
    }
    
    /**
     * 分销中心
     */
    public function distribution_center()
    {
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('参数异常!');
        }
      //分销商信息
      $res = Db::name('distributor')->where('id',$param['fid'])->find();
      if(!$res) $this->error('您当前还不是分销商,请前往申请');
      if($res['status'] == 1) $this->error('您的分销权限已被禁用,请联系管理员解禁!');
      if($res['examine'] == 0) $this->error('您的分销商申请正在审核中,请耐心等待!');
      if($res['examine'] == 2) $this->error('您的分销商申请已被拒接,请联系管理员!');
       // 可提现佣金
       $commission  = $res['commission'];
       // 累积提现佣金
       $endmoney = $res['endmoney'];
       // 昨日收益
       $list = Db::name('user')->where('superior_fid',$param['fid'])->select()->toArray();
           $price = 0;
       foreach ($list as $k => $v) {
           // 查询下级用户 昨天 已完成 订单
           $price += Db::name('order')->where('uid',$v['id'])->where('status',4)->whereDay('completion_time', 'yesterday')->sum('total_price');
       }
       // 提成比例
       $propor= sysconfig('contact', 'distribution_commission_ratio') / 100;
       //收益
       $profit = $price * $propor;
        // 团队人数
       $num = count($list);
       $this->success('获取成功', compact('commission','endmoney','profit','num','res'));
    }


    /**
     *  我的团队
     */
    public function tem()
    {
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('参数传递错误!');
        }
        $where = [];
        if(!empty($param['nickname']) && isset($param['nickname']))
        {
            $where['nickname'] = $param['nickname'];
        }
        $list = Db::name('user')->where('superior_fid',$param['fid'])->where($where)->select()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['pricenum'] =  Db::name('order')->where('uid',$v['id'])->where('status',4)->sum('total_price');  // 订单金额
            $list[$k]['ordernum'] = Db::name('order')->where('uid',$v['id'])->where('status',4)->count(); // 订单数量
        }
        $this->success('获取成功', $list);
    }  

    //分销订单
    public function distribution_order(){
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('参数传递错误!');
        }
        $list = Db::name('commission_record')
             ->where('superior_fid',$param['fid'])
             ->where('type',2)
             ->field("id,uid,oid,money,create_time")
             ->paginate(10)->each(function($item){
                 $user = Db::name("user")->where("id",$item["uid"])->field("nickname,avatar")->find();
                 $order = Db::name("order")->where("id",$item["oid"])->field("order_no")->find();
                 $item["nickname"] = $user["nickname"];
                 $item["avatar"] = $user["avatar"];
                 $item["order_no"] = $order["order_no"];
                 if(!empty($item["create_time"])){
                    $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                 }else{
                    $item["create_time"] = "";
                 }
                return $item;
             });
        $this->success('获取成功', $list);
    }

    //分销商协议
    public function get_distributor_agreement(){
      $distributor_agreement = sysconfig('contact','distributor_agreement');
      $distributor_agreement = html_entity_decode($distributor_agreement);
      $distributor_agreement = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $distributor_agreement);
      $this->success('获取成功', $distributor_agreement);
    }

    //分销商海报
    public function get_distributor_poster(){
        $list = Db::name("banner")->where("type",4)->select();
        $this->success('获取成功', $list);
    }

    //扫码绑定上级
    public function scan_code_binding(){
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('分销商id不能为空!');
        }
        //判断用户是否是分销商
        $user = Db::name("user")->where("id",$this->uid)->find();
        if($user["fid"] > 0){
            $this->error('分销商不能成为下级!');
        }
        //判断是否有上级
        if($user["superior_fid"] > 0){
            $this->error('已绑定,不能重复绑定!');
        }
        Db::name("user")->where("id",$this->uid)->update(["superior_fid"=>$param["fid"],"superior_time"=>time()]);
        $this->success('绑定成功');
    }



  
  

  
   

}
